package com.yangming.service.impl;

import com.yangming.common.base.Constants;
import com.yangming.mapper.UserMapper;
import com.yangming.model.User;
import com.yangming.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author PengShuiMing
 * @create 2018-09-07
 **/
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 新增用户
     * @param user
     * @return
     */
    @Override
    public int saveUser(User user) {
        return userMapper.insertSelective(user);
    }

    @Override
    public User selectUserByOpenId(String openId) {
        User resultUser = new User();
        //从redis获取用户
        Object obj = redisTemplate.opsForValue().get(Constants.SXZ_USER_INFO_PREFIX + openId);
        if(null!=obj){
            resultUser = (User) obj;
        }else{
            //从数据库查询
            User user = userMapper.selectUserByOpenId(openId);
            if (null!=user){
                resultUser =user;
            }else {
                //没有新建用户
                resultUser.setOpenId(openId);
                resultUser.setType(1);
                userMapper.insertSelective(resultUser);
            }
            //放进redis
            redisTemplate.opsForValue().set(Constants.SXZ_USER_INFO_PREFIX + openId,resultUser);
        }
        return resultUser;
    }
}
